<template>
    <!--物资验收修改 -->
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div
            class="tabs warningTabs"
            v-if="Object.keys(formData).length != 0"
        >
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="验收明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="serviceCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="验收编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="所属机构">
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="业务类型"
                                                    prop="businessType"
                                                >
                                                    {{
                                                        businessType
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="源单编号">
                                                    <span>
                                                        {{
                                                            formData.sourceBillNo
                                                        }}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                sourceBillNoClick
                                                            "
                                                            v-if="
                                                                formData.sourceBillNo  && formData.businessType !== 3
                                                            "
                                                        ></i>
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商"
                                                    prop="supplierName"
                                                >
                                                    {{
                                                        formData.supplierName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="采购人员"
                                                    prop="purchaserName"
                                                >
                                                    {{
                                                        formData.purchaserName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(元)"
                                                    prop="acceptanceAmount"
                                                >
                                                    {{
                                                        formData.acceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="验收人员">
                                                    {{
                                                        formData.acceptancerName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验结一体"
                                                    :prop="
                                                        formData.isAccepSettle
                                                            ? 'invoiceNo'
                                                            : 'invoiceNos'
                                                    "
                                                >
                                                    <el-checkbox
                                                        v-model="
                                                            formData.isAccepSettle
                                                        "
                                                        label=""
                                                        style="
                                                            margin-right: 10px;
                                                        "
                                                        disabled
                                                    ></el-checkbox>
                                                    <span
                                                        v-show="
                                                            formData.isAccepSettle
                                                        "
                                                        >{{
                                                            formData.invoiceNo
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期"
                                                    prop="acceptanceDate"
                                                >
                                                    {{
                                                        formData.acceptanceDate
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    {{ formData.taxRate }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="服务费用(元)"
                                                    prop='freight'
                                                >
                                                    {{ formData.freight }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                    {{
                                                        formData.taxAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="税价合计" prop='totalAmount'>
                                                    {{
                                                        formData.totalAmount
                                                    }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                    {{ formData.currency }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{
                                                        formData.baseCurName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    {{
                                                        formData.baseCurRate
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <!-- <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(本位币)"
                                                >
                                                    {{
                                                        formData.baseCurAcceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col> -->

                                            <el-col :span="12">
                                                <el-form-item label="结算编号" v-show='formData.settleNo'>
                                                    <span style="color: blue;cursor: pointer;" @click='settlementNoClick'>{{formData.settleNo}}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                                <!-- <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    resize="none"
                                                    placeholder="请输入内容"
                                                    v-model="
                                                        formData.remarks
                                                    "
                                                    v-if="isRedSingle"
                                                >
                                                </el-input> -->
                                                <!-- 如果是冲红单单据,可对备注进行编辑 -->
                                                <span>{{
                                                    formData.remarks
                                                }}</span>
                                            </el-form-item>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                    <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12" v-if="formData.redBillState !== -1">
                                                <!-- 仅发生冲红单业务时,才显示该字段,暂未做判断 -->
                                                <el-form-item label="冲红单">
                                                    <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDescription
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 验收明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            验收明细
                        </div>
                        <div class="e-table">
                            <!-- <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="small"
                                            style="
                                                background: rgb(75, 178, 255);
                                                color: #fff;
                                            "
                                            @click="selectReceipt"
                                            >选择收料</el-button
                                        >
                                        <el-button
                                            size="small"
                                            style="
                                                background: #7aa818;
                                                color: #fff;
                                            "
                                            >删除</el-button
                                        >
                                    </div>
                                </div>
                            </div> -->
                            <!-- <div
                                class="errorMsg"
                                v-if="errorAcceptanceMsg.length > 0"
                            >
                                <span>
                                    {{ errorAcceptanceMsg.join(',') }}
                                </span>
                            </div> -->
                            <el-table
                                :data="acceptanceData"
                                ref='acceptanceRef'
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :row-class-name="tableRowClassName"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': acceptanceData, '_this': this, 'ref': 'acceptanceRef' }"
                            >
                                <!-- <el-table-column type="selection" width="55">
                                </el-table-column> -->
                                <!-- <el-table-column
                                    label="操作"
                                    fixed
                                    align="center"
                                    v-if="isBatch"
                                >
                                    <template v-slot="{ row, $index }">
                                        <i
                                            class="el-icon-delete"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                                color: red;
                                            "
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterId == row.dtlId
                                            }"
                                            @click="acceptanceDelete(row)"
                                            v-if="$index > 0"
                                        ></i>
                                    </template>
                                </el-table-column> -->
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    fixed
                                    min-width="170"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="100"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="notAcceptedQuantity"
                                    label="未验收数量"
                                    width="100"
                                >
                                <template v-slot="{ row }">
                                    <span v-if="!row.children">{{
                                            +(+row.notAcceptedQuantity -
                                            +row.acceptanceQuantity).toFixed(2)
                                        }}</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="验收数量"
                                    width="120"
                                    prop="acceptanceQuantity"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="验收单价（元）"
                                    width="110"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="验收金额（元）"
                                    width="120"
                                    prop="acceptanceAmount"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="serviceChargeCon" class="con">
                        <div class="tabs-title" id="serviceCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <!-- <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="small"
                                            style="
                                                background: rgb(75, 178, 255);
                                                color: #fff;
                                            "
                                            @click="serviceFeeAdd"
                                            >新增行</el-button
                                        >
                                        <el-button
                                            size="small"
                                            style="
                                                background: #7aa818;
                                                color: #fff;
                                            "
                                            >删除</el-button
                                        >
                                    </div>
                                </div>
                            </div> -->
                            <!-- <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div> -->
                            <el-table
                                :data="serviceFeeData"
                                ref='serviceFeeTableRef'
                                border
                                style="width: 100%"
                                @selection-change="serviceFeeSelect"
                                :row-class-name="tableRowClassNameF"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTableRef' }"
                            >
                                <el-table-column type="selection" width="55">
                                </el-table-column>
                                <!-- <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="isBatch"
                                >
                                    <template v-slot="{ row }">
                                        <i
                                            class="el-icon-delete"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                                color: red;
                                            "
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterIdF == row.dtlId
                                            }"
                                            @click="serviceFeeDelete(row)"
                                        ></i>
                                    </template>
                                </el-table-column> -->
                                <el-table-column
                                    label="合同编号"
                                    fixed
                                    min-width="150"
                                    prop="contractBillNo"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    fixed
                                    min-width="190"
                                    prop="settlementUnitName"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="清单名称"
                                    width="100"
                                    prop="contractDtlName"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="数量"
                                    width="100"
                                    prop="quantity"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="金额(元)"
                                    width="100"
                                    prop="amount"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="发票编号"
                                    width="130"
                                    prop="invoiceNo"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="税率%"
                                    width="130"
                                    prop="taxRate"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="税额（元）"
                                    width="130"
                                    prop="taxAmount"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计（元）"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            :isView='true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="1015"
                            :billId="billid"
                            @historyTableHeight='historyTableHeight'
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons" v-if='!isview'>
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state == 1 ||
                    formData.state == 9 ||
                    formData.state == 2
                "
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state == 2 &&
                    (formData.redBillState === '' ||
                        formData.redBillState === -1)
                "
                @click="redSingle"
                >冲红单</el-button
            >
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                @click="saveRedList"
                v-if="isRedSingle"
                >保存</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="submitRedList"
                v-if="isRedSingle"
                >保存并提交</el-button
            > -->
            <exaButtons :auditState="auditState" @exas="exas" v-if="formData.state !== 5" :state='formData.state' :founderId='formData.founderId' :multiple="formData.state === 1 || formData.state === 2" :commandList='commandList'></exaButtons>
            <!-- <el-button type="primary" style="background: #2e61d7"
                >审核</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="submit()"
                >保存并提交</el-button
            >

            <el-button type="primary" style="background: #2e61d7"
                >撤回</el-button
            >
            <el-button type="danger" size="small" @click="ctDelete"
                >删除</el-button
            >
            <el-button type="primary" style="background: #2e61d7"
                >作废</el-button
            > -->
            <el-button @click="handleClose">关闭</el-button>
        </div>
        <span style="display: none">{{ localPopConfirm }}</span>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {
    showPromptPop,
    showSuccessPop,
    selectDataClient,
    showLoading,
    hideLoading,
    openAppClient
} from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/materials/materialAcceptance'
import { getUuid } from '@/utils/common'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'
import exaButtons from '@/components/common/exaButtons'
import { webprintReport, numToChinese } from '@/utils/common'

export default {
    components: {
        AttachComp,
        AcceptanceHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            acceptanceData: [], // 验收明细数据
            serviceFeeData: [], //服务费用数据
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                businessType: '', //业务类型
                sourceBillNo: '', //源单编号
                supplierName: '', //供应商
                purchaserName: '', //采购人员
                purchasingUnitName: '', //采购单位
                acceptancerName: '', //验收人员
                acceptanceAmount: '', //验收金额
                acceptanceDate: '', //验收日期
                isAccepSettle: '', //验结一体
                freight: '', //运输单位费用
                taxRate: '', //税率
                totalAmount: '', //税价合计
                taxAmount: '', //税额
                currency: '', //币种
                showEas: '', //传财务共享
                baseCurAcceptanceAmount: '', //验收金额
                baseCurName: '', //本位币
                settleNo: '', //结算编号
                remarks: '', //备注
                redBillState: '',
                state: '', //状态
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurFreight: 0,
                baseCurId: '',
                baseCurRate: 0,
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                rmbAcceptanceAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                sourceBillId: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                workId: '',
                redBillId: '',
                redBillNo: '',
                isRed: 0
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转,
            businessTypeList: [
                {
                    value: 0,
                    key: '零星采购计划'
                },
                {
                    value: 1,
                    key: '物资采购合同'
                },
                {
                    value: 2,
                    key: '内部调拨'
                },
                {
                    value: 3,
                    key: '事实合同'
                }
            ],
            formDataRules: {
                businessType: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                supplierName: [
                    { required: true, message: '请选择供应商', trigger: 'blur' }
                ],
                purchaserName: [
                    { required: true, message: '请选择采购人员', trigger: 'blur' }
                ],
                acceptanceAmount: [
                    { required: true, message: '请输入验收金额', trigger: 'blur' }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                totalAmount: [
                    { required: true, message: '请输入税价合计', trigger: 'blur' }
                ],
                freight: [
                    { required: true, message: '请输入服务费用', trigger: 'blur' }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],
                invoiceNo: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ]
            },
            isBatch: true,
            MouseEnterId: null,
            serviceFeeRow: {
                amount: 0,
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: 0,
                quantity: 0,
                settlementUnitId: '',
                settlementUnitName: '',
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0
            },
            billingUnitQuery: {
                businessUnitTypes: [],
                keyword: '',
                limit: 2,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: []
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: '1015',
                cwAuditState: 0,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                returnEmpId: '',
                returnEmpName: '',
                userId: '',
                workId: '',
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1015',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorAcceptanceMsg: [], // 验收明细
            errorServiceFeeMsg: [], // 服务费用
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isRedSingle: false,
            historyData: [],
            businessType: '',
            isview: false, // 如果是别的页面弹出此页面,需要隐藏下面的按钮
            commandList: [
                { key: 1, value: '验收单' },
                { key: 2, value: '服务费验收单' }
            ],
            prnTitl: [
                { key: 1, value: '物资验收单' },
                { key: 2, value: '物资采购服务费验收单' }
            ],
            serviceFeeList: []
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        // //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },
        // 税价合计
        totalAmountFun () {
            return (
                +this.formData.acceptanceAmount +
                +this.formData.taxAmount
            )
        },
        localPopConfirm () {
            if (this.popConfirm) {
                switch (this.popStatus) {
                case 'prompt':
                    this.delData()
                    break
                case 'success':
                    if (this.isSkip) this.handleClose()
                    break
                }
                this.setPopConfirm(false)
            }
            return this.popConfirm
        },
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            console.log('this.screenHeight', this.screenHeight)
            console.log('this.lastConHeight', this.lastConHeight)
            return this.screenHeight - 20 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.isAccepSettle' () {
            // 如果验结一体未勾选,则需要清除发票号的提示信息
            if (!this.formData.isAccepSettle) {
                this.$refs.formDataRef.clearValidate('invoiceNo')
                this.formData.invoiceNo = ''
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.getAllData()
        if(this.$route.query.isview === 'true' || this.$route.query.isview === 'false') {
            this.isview = JSON.parse(this.$route.query.isview)
        }
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'receivingMaterials',
            'serviceCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicData(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicData () {
            try {
                showLoading()
                let data = await request.getGoodsCheckbasicInfo(this.billid)

                // if(!data) return
                this.businessType = this.businessTypeList.find(
                    item => item.value === data.businessType
                ).key
                data.currency = this.currencyForm.find(
                    x => x.value === data.currencyId
                ).label

                this.formData = data
                await this.getAcceptanceList() // 验收明细表格数据
                await this.getServeList() // 服务费用表格数据
            } finally {
                hideLoading()
            }
        },
        // 源单编号
        sourceBillNoClick () {
            let url = ''
            let name = ''
            switch (this.formData.businessType) {
            case 0:
                url = '/sporadicPurchaseParticulars'
                name = '查看零星采购计划'
                break
            case 1:
                url = '/ctMaterialApplyShow'
                name = '查看物资采购合同'
                break
            case 2:
                url = '/interiorAllotEetails'
                name = '查看内部调拨'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceBillId}&isview=${true}`,
                `${name}`
            )
        },
        // 结算编号-跳转到物资结算详情页
        settlementNoClick () {
            openAppClient(
                `/materialProcurementView?isview=${true}&billid=${
                    this.formData.settleId
                }`,
                '查看物资结算'
            )
        },

        // 供应商处: 选择收料明细
        supplierNameClick () {
            // 打开弹窗时,调下面函数获取弹窗的数据
            selectDataClient({
                SelectServiceToken: '', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
                // InitParamsStr: JSON.stringify({ name: '' }),    // 接口参数(name为模拟参数)
                Title: '选择明细' // 标题
            }).then(val => {
                // val是关闭弹窗后,返回的数据
                this.formData.supplierName = val[0].supplierName // 供应商
                this.formData.supplierId = val[0].supplierId // 供应商ID
                this.formData.purchaserName =
                    val[0].purchasingPersonnelName // 采购人员名称
                this.formData.purchaserId = val[0].purchasingPersonnelId // 采购人员ID
                // 如果选择的是零星采购计划，物资采购合同，调拨单这三种,需要调接口获取币种,本位币,如果是物资采购合同：还需要带入合同税率
                if (this.formData.businessType !== 3) {
                    this.$Ajax
                        .httpGet({
                            url: '/material/siteReceiving/getSourceBillInfo',
                            params: {
                                billId: val[0].billId
                            }
                        })
                        .then(res => {
                            this.formData.currency = res.currency // 币种名称
                            this.formData.currencyId = res.currencyId // 币种ID
                            this.formData.baseCurName = res.baseCurName // 本位币名称
                            this.formData.baseCurId = res.baseCurId // 本位币ID
                            this.formData.taxRate = res.taxRate // 物资采购合同：带入合同税率。
                        })
                }
            })
        },

        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },

        // ------------------------------验收明细---------------------------------------

        // 获取验收明细表格数据(弹窗好了过后最终需要调的接口)
        async getAcceptanceList () {
            let res = await request.getAcceptanceList(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = item.children.reduce(
                    (prev, c) => (prev += c.acceptanceAmount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.acceptanceData = res
        },
        // 在点击选择收料弹窗的保存按钮时,需要对数据所做的处理,res就是关闭弹窗后返回的数据(无弹窗时调的接口)
        // 选择收料
        // selectReceipt () {
        //     selectDataClient({
        //         SelectServiceToken: '', // 客户端对应方法名
        //         IsSingleMode: false, // 是否单选 true 单选 false 多选
        //         SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
        //         // InitParamsStr: JSON.stringify({ name: '' }),    // 接口参数(name为模拟参数)
        //         Title: '选择明细' // 标题
        //     }).then(res => {

        // async getAcceptanceList () { // 弹窗好了,需删除这行
        //     let res = await request.getAcceptanceList({ // 弹窗好了,需删除这行
        //         businessType: this.formData.businessType, // 弹窗好了,需删除这行
        //         orgId: this.orgId // 弹窗好了,需删除这行
        //     }) // 弹窗好了,需删除这行

        //     if (!res) {
        //         return
        //     } else {
        //         const mapObj = {}
        //         let arr = []
        //         if (!Array.isArray(res)) return
        //         res.forEach(b => {
        //             const children = []
        //             this.formData.sourceId = b.children[0].billId
        //             // this.formData.sourceNumber = b.children[0].billNo
        //             b.children.forEach(e => {
        //                 e.materialClassNameArr = e.materialClassName.split('/')
        //                 e.materialClassIdArr = e.materialClassId.split('/')
        //                 let obj
        //                 const topClassId = e.materialClassIdArr
        //                     .splice(0, 1)
        //                     .toString()
        //                 const topClassName = e.materialClassNameArr
        //                     .splice(0, 1)
        //                     .toString()
        //                 if (!mapObj[topClassId]) {
        //                     obj = {
        //                         topClassId,
        //                         topClassName,
        //                         customId: topClassId,
        //                         materialClassId: topClassId,
        //                         materialClassName: topClassName,
        //                         uuid: getUuid(),
        //                         totalAmount: null,
        //                         totalQuantity: null
        //                     }
        //                     //这里需要改成push多个对象   还没改
        //                     arr.push(obj)

        //                     mapObj[topClassId] = obj
        //                 } else {
        //                     obj = mapObj[topClassId]
        //                 }

        //                 // 物资名称
        //                 children.push({
        //                     uuid: getUuid(),
        //                     customId: getUuid(),
        //                     acceptanceQuantity: e.acceptedQuantity
        //                         ? e.acceptedQuantity
        //                         : e.notAcceptedQuantity, //已验收数量
        //                     billId: this.billid, //	验收ID
        //                     changeType: 1, //变更类型
        //                     dtlId: '', //验收明细ID
        //                     materialClassId: e.materialClassIdArr.join('/'), //物资类别id
        //                     materialClassName: e.materialClassNameArr.join('/'), // 物资类别名称
        //                     materialId: e.materialId, //物资id
        //                     materialName: e.materialName, //物资名称
        //                     notAcceptedQuantity: e.notAcceptedQuantity, // 未验收数量
        //                     sourceDtlId: e.dtlId, //源单明细id
        //                     spec: e.spec, //规格型号
        //                     texture: e.texture, //材质
        //                     unit: e.unit, //计量单位
        //                     warehouseId: e.warehouseId, //仓库id
        //                     warehouseName: e.warehouseName,
        //                     acceptanceAmount: 0,
        //                     price: 0,
        //                     settledQuantity: 0,
        //                     unsettledQuantity: 0
        //                 })
        //                 obj.children = !obj.children
        //                     ? children
        //                     : obj.children.concat(children)
        //                 // 统计小计
        //                 const count = obj.children.reduce(
        //                     (prev, c) => (prev += c.acceptanceAmount || 0),
        //                     0
        //                 )
        //                 obj.materialName = `金额小计： ${count}`
        //                 obj.children = this.uniqueArray(
        //                     obj.children,
        //                     'customId'
        //                 )
        //             })
        //         })
        //         this.acceptanceData = arr
        //         console.log(this.acceptanceData)
        //     }
        // },
        // })
        // },
        // },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },

        // 监听验收数量
        acceptanceQuantityBlur (row) {
            row.changeType = 2
            if (
                row.notAcceptedQuantity &&
                row.acceptanceQuantity > row.notAcceptedQuantity
            ) {
                row.acceptanceQuantity = ''
                row.price = 0
            } else {
                if (!!row.acceptanceAmount && !!row.acceptanceQuantity) {
                    row.price = +row.acceptanceAmount / +row.acceptanceQuantity
                }
            }
        },

        // 监听验收金额
        acceptanceAmountBlur (row) {
            row.changeType = 2
            row.price = +row.acceptanceAmount / +row.acceptanceQuantity
        },

        //删除验收明细
        acceptanceDelete (row) {
            row.changeType = -1
        },
        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        // ---------------------------------服务明细---------------------------------
        // 点击新增行
        serviceFeeAdd () {
            this.serviceFeeData.push(this.serviceFeeRow)
        },

        // 合同选择弹窗

        contractDialog () {},
        billingUnitDialog () {},

        // 获取服务费用表格数据(弹窗做好后,需要放开注释的)
        async getServeList () {
            let res = await request.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },

        // 结算单位弹窗选择点击保存后
        // billingUnitDialog () {
        //     selectDataClient({
        //         SelectServiceToken: '', // 客户端对应方法名
        //         IsSingleMode: false, // 是否单选 true 单选 false 多选
        //         SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
        //         // InitParamsStr: JSON.stringify({ name: '' }),    // 接口参数(name为模拟参数)
        //         Title: '选择明细' // 标题
        //     }).then(res => {

        // async getServeList () { // 弹窗好了,需删除这行
        // let res = await request.getServeList(this.billingUnitQuery) // 弹窗好了,需删除这行
        // let result = res.list.map(item => {
        //     return {
        //         amount: 0,
        //         billId: this.billid,
        //         changeType: 1,
        //         contractBillId: '',
        //         contractBillNo: '',
        //         contractDtlId: '',
        //         contractDtlName: '',
        //         dtlId: '',
        //         invoiceNo: '',
        //         price: 0,
        //         quantity: 0,
        //         settlementUnitId: item.outerId,
        //         settlementUnitName: item.outerName,
        //         taxAmount: 0,
        //         taxRate: 0,
        //         totalAmount: 0
        //     }
        // })
        //     if(Array.isArray(res)) {
        //         this.serviceFeeData = res
        //     }
        // },

        // })
        // },
        // },

        // 数量变化时
        quantityBlur (row) {
            row.changeType = 2
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
        },
        // 金额变化时
        amountBlur (row) {
            row.changeType = 2
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = row.amount * row.taxRate
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalAmount = row.amount + row.taxAmount
            }
        },
        // 编号变化时
        invoiceNoBlur (row) {
            row.changeType = 2
        },
        // 税率变化时
        taxRateBlur (row) {
            row.changeType = 2
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = row.amount * row.taxRate
            }
        },
        //税额变化时
        taxAmountBlur (row) {
            row.changeType = 2
            if (!!row.amount && !!row.taxAmount) {
                row.totalAmount = +row.amount + +row.taxAmount
            }
        },
        // 服务费用单条删除
        serviceFeeDelete (row) {
            row.changeType = -1
        },
        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        // 复选框选中的数据
        serviceFeeSelect (selection) {
            this.serviceFeeList = selection
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置验收明细有错误时在表格上面显示的错误信息
        setErrorAcceptanceMsg (msg) {
            let index = this.errorAcceptanceMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorAcceptanceMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        request
                            .saveGoodsCheckEdit(this.formData)
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存验收明细时需要检测的
        saveAcceptance () {
            this.errorAcceptanceMsg = []
            return new Promise((resolve, reject) => {
                this.acceptanceData.forEach(item => {
                    !item.materialClassName
                        ? this.setErrorAcceptanceMsg('请填写物资类别')
                        : ''
                    !item.materialName
                        ? this.setErrorAcceptanceMsg('请填写物资名称')
                        : ''
                    // !item.unit ? this.setErrorAcceptanceMsg('请填写计量单位') : ''
                    // !item.warehouseName
                    //     ? this.setErrorAcceptanceMsg('请填写仓库')
                    //     : ''
                    // !item.notAcceptedQuantity
                    //     ? this.setErrorAcceptanceMsg('请填写未验收数量')
                    //     : ''
                    // !item.acceptanceQuantity
                    //     ? this.setErrorAcceptanceMsg('请填写验收数量')
                    //     : ''
                    // !item.price
                    //     ? this.setErrorAcceptanceMsg('请填写验收单价(元)')
                    //     : ''
                    // !item.acceptanceAmount
                    //     ? this.setErrorAcceptanceMsg('请填写验收金额(元)')
                    //     : ''
                })
                console.log(this.errorAcceptanceMsg)
                if (this.errorAcceptanceMsg.length > 0) {
                    this.setError('receivingMaterials')
                    reject('验收明细错误')
                    return
                } else {
                    request
                        .saveAcceptanceData(this.acceptanceData)
                        .then(() => {
                            this.clearError('receivingMaterials')
                            resolve()
                        })
                        .catch(err => {
                            this.errorAcceptanceMsg[0] = err.message
                            this.setError('receivingMaterials')
                            reject(err)
                        })
                }
            })
        },
        // 保存服务明细时需要检测的
        saveServiceFee () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 如果是基本信息处验结一体勾选中，则服务费用明细中发票编号必填
                if (this.formData.isAccepSettle) {
                    this.serviceFeeData.every(item => {
                        if (!item.invoiceNo) {
                            return this.setErrorServiceFeeMsg('请填写发票编号')
                        }
                    })
                }
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    !item.settlementUnitName
                        ? this.setErrorServiceFeeMsg('请填写结算单位')
                        : ''
                    // !item.contractDtlName
                    //     ? this.setErrorServiceFeeMsg('请填写清单名称')
                    //     : ''
                    // !item.quantity
                    //     ? this.setErrorServiceFeeMsg('请填写数量')
                    //     : ''
                    // !item.price
                    //     ? this.setErrorServiceFeeMsg('请填写单价(元)')
                    //     : ''
                    // !item.amount
                    //     ? this.setErrorServiceFeeMsg('请填写金额(元)')
                    //     : ''
                    // !item.totalAmount
                    //     ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                    //     : ''
                })
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('serviceCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    request
                        .saveServiceFeeData(this.serviceFeeData)
                        .then(() => {
                            this.clearError('serviceCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('serviceCharge')
                            reject(err)
                        })
                }
            })
        },
        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.saveAcceptance(),
                this.saveServiceFee()
            ])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提交审核
        submitReview () {
            if (this.formData.isAccepSettle) {
                this.clientPop(
                    'info',
                    '验结一体将生成一笔相同金额的采购结算单,请确认执行操作!',
                    this.callback,
                    null,
                    () => {
                        showLoading()
                        this.errorList = []
                        Promise.all([
                            this.updateBaseInfo(),
                            this.saveAcceptance(),
                            this.saveServiceFee()
                        ])
                            .then(() => {
                                request
                                    .commitAudit(this.auditParams)
                                    .then(() => {
                                        this.clientPop(
                                            'suc',
                                            '提交成功',
                                            this.handleClose
                                        )
                                    })
                                    .catch(err => {
                                        // 需求文档中,提交/审核 -> 第7条
                                        this.clientPop(
                                            'info',
                                            err,
                                            this.callback,
                                            null,
                                            this.cancelCallBack
                                        )
                                    })
                            })
                            .catch(err => {
                                console.log('errMsg：', err)
                                this.clientPop('err', '提交失败', () => {
                                    this.scorllError()
                                })
                            })
                            .finally(() => {
                                hideLoading()
                            })
                    }
                )
            }
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            this.clientPop('info', '确定返回上一步操作吗?', () => {
                showLoading()
                // this.setSelectedInfo(this.auditParams)
                // openAppClient('/showSelectedData', '选择结果')
                try{

                    request.undoAudit(this.auditParams).then(() => {
                        this.clientPop('suc', '撤回成功', this.handleClose)
                    }).finally(() => {
                        hideLoading()
                    })
                }catch(err) {
                    alert(err)
                }
            })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request.nullify(auditParams).then(() => {
                    hideLoading()
                    this.clientPop('suc', '作废成功', this.handleClose)
                })
            }, null, null, null, 'small')
        },
        // 删除
        deleteData () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    request.deleteData(this.billid).then(() => {
                        hideLoading()
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        // 打印
        async print (value) {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [], // 基本信息
                        'tables': [] //表格
                    }
                    const reportTitle = this.prnTitl.find(item=>item.key == value)
                    params.reportTitle = reportTitle.value
                    let tableObj = {}
                    if(reportTitle.key === 1) {
                        tableObj = {
                            1: this.ReceivingRpt()
                        }
                    }else {
                        tableObj = {
                            1: this.ReceivingRpt(),
                            2: this.ServAcceptanceCertificate()
                        }
                    }
                    const tableData = tableObj[reportTitle.key]
                    params.summaryInfoItems = tableData.basicInfo
                    params.tables.push(tableData.tableList)
                    params.tables.push(await this.auditHst())
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 验收单
        ReceivingRpt () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['供货单位', data.supplierName, false],
                ['附件', '    ' + '张', false],
                ['验收依据', data.sourceBillNo, false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', data.acceptanceAmount, false],
                ['税率(%)', data.taxRate + '%', false],
                ['可抵扣税额(元)', data.taxAmount, false],
                ['价税合计金额(元)', data.totalAmount, false],
                ['价税合计金额大写', numToChinese(Math.abs(data.totalAmount)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            let newArr = this._.cloneDeep(this.acceptanceData)
            let lastArr = []
            newArr.forEach(item => {
                lastArr.push(item)
                if(item.children.length > 0) {
                    lastArr.push(...item.children)
                }
            })
            const tableList = {
                'tableTitle': '验收明细',
                'tableContent': {
                    '物资类别': 'materialClassName',
                    '物资名称': 'materialName',
                    '规格': 'spec',
                    '材质': 'texture',
                    '单位': 'unit',
                    '验收数量': 'acceptanceQuantity',
                    '验收单价(元)': 'price',
                    '验收金额(元)': 'acceptanceAmount',
                },
                'tableData': lastArr, //表格数据
            }
            return { basicInfo, tableList }
        },
        // 服务费验收单
        ServAcceptanceCertificate () {
            if(this.serviceFeeData.length > 0) {
                if(this.serviceFeeList.length < 1) {
                    this.serviceFeeList = this._.cloneDeep(this.serviceFeeData)
                    return this.FmtData(this.serviceFeeList)
                }else {
                    return this.FmtData(this.serviceFeeList)
                }
            }else {
                this.clientPop('err', '服务费用无明细可打印')
                return
            }
        },
        // 格式数据
        FmtData (data) {
            // 是否相同结算单位
            const isTheSm = data.some(item =>data[0].settlementUnitId !== item.settlementUnitId)
            // 是否相同税率
            const isSmRt = data.some(item =>data[0].taxRate !== item.taxRate)
            if(isTheSm || isSmRt) {
                this.clientPop('err', '需选择相同结算单位和相同税率的数据,请先选择!')
                return
            }else {
                // 如果都是相同结算单位并且相同税率
                const obj = data.reduce((prev, c) => {
                    prev.amount += +(+c.amount).toFixed(2),
                    prev.totalAmount += +(+c.totalAmount).toFixed(2),
                    prev.taxAmount += +(+c.taxAmount).toFixed(2)
                    return prev
                }, { amount: 0, totalAmount: 0, taxAmount: 0, })
                obj.settlementUnitName = data[0].settlementUnitName
                obj.contractBillNo = data[0].contractBillNo
                obj.taxRate = data[0].taxRate
                return this.servPrnSelectFn(obj)
            }
        },
        servPrnSelectFn (obj) {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['服务单位', obj.settlementUnitName, false],
                ['附件', '    ' + '张', false],
                ['验收依据', obj.contractBillNo, false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', obj.amount, false],
                ['税率(%)', obj.taxRate + '%', false],
                ['可抵扣税额(元)', obj.taxAmount, false],
                ['价税合计金额(元)', obj.totalAmount, false],
                ['价税合计金额大写', numToChinese(Math.abs(obj.totalAmount)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            const tableList = {
                'tableTitle': '服务费明细',
                'tableContent': {
                    '结算单位': 'settlementUnitName',
                    '清单名称': 'contractDtlName',
                    '发票编号': 'invoiceNo',
                    '数量': 'quantity',
                    '单价(元)': 'price',
                    '金额': 'amount',
                    '税率': 'taxRate',
                    '税额': 'taxAmount',
                    '税额合计': 'totalAmount',
                },
                'tableData': this.serviceFeeList, //表格数据
            }
            return { basicInfo, tableList }
        },
        // 审核历史
        async auditHst () {
            //审核历史
            const historyTable  = await request.getAuditHistory(this.auditParams)
            const historyList = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '通知时间': 'notifyTime',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': historyTable, //表格数据
            }
            return historyList
        },
        // 点击冲红单
        async redSingle () {
            try {
                await request.isRedSingleFn(this.billid)
                this.$router.replace({
                    path: '/goodsCheckAdd',
                    query: { isRedSingle: '1', billid: this.billid }
                })
            }catch(err) {
                console.log(err)
            }
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.deleteData() // 删除
            } else if(arg.type === 'multiple') {
                this.print(arg.value) // 打印
            }
        },

        // ------------------------上面小刘---------

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon') && this.historyData.length > 0) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },

        ctDelete () {
            showPromptPop(
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。'
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/materialsettle/acceptance/delete',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./goodsCheck')
                })
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/goodsCheck')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
